<template>
  <div>
    <!-- 新增记录按钮 -->
    <div class="action-bar">
      <a-button type="primary" @click="showModal = true">新增记录</a-button>
    </div>
    
    <!-- 新增记录模态框 -->
    <a-modal
      v-model:visible="showModal"
      title="新增健康记录"
      :confirm-loading="saving"
      @ok="submitForm"
      @cancel="handleCancel"
      destroyOnClose
      width="800px"
    >
      <a-form layout="vertical" :model="formData">
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="性别" name="gender" :rules="[{ required: true, message: '请选择性别' }]">
              <a-select v-model:value="formData.gender" placeholder="请选择性别">
                <a-select-option value="男">男</a-select-option>
                <a-select-option value="女">女</a-select-option>
              </a-select>
            </a-form-item>
            
            <a-form-item label="出生日期" name="birthday">
              <a-date-picker 
                v-model:value="formData.birthday" 
                placeholder="请选择生日" 
                style="width: 100%" 
                :disabled-date="disabledBirthdayDate"
              />
            </a-form-item>
            
            <a-form-item 
              label="身高 (cm)" 
              name="height" 
              :rules="[{ required: true, message: '请输入身高' }]"
            >
              <a-input-number 
                v-model:value="formData.height" 
                :min="100" 
                :max="250" 
                style="width: 100%" 
                placeholder="正常范围：150~190"
              />
            </a-form-item>
            
            <a-form-item 
              label="体重 (kg)" 
              name="weight" 
              :rules="[{ required: true, message: '请输入体重' }]"
            >
              <a-input-number 
                v-model:value="formData.weight" 
                :min="30" 
                :max="200" 
                style="width: 100%" 
                placeholder="正常范围：45~90"
              />
            </a-form-item>
            
            <a-form-item label="血型" name="bloodType">
              <a-select v-model:value="formData.bloodType" placeholder="请选择血型">
                <a-select-option value="A">A型</a-select-option>
                <a-select-option value="B">B型</a-select-option>
                <a-select-option value="AB">AB型</a-select-option>
                <a-select-option value="O">O型</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item label="血压 (mmHg)" name="bloodPressure">
              <a-input 
                v-model:value="formData.bloodPressure" 
                placeholder="格式：120/80"
              />
            </a-form-item>
            
            <a-form-item label="心率 (bpm)" name="heartRate">
              <a-input-number 
                v-model:value="formData.heartRate" 
                :min="30" 
                :max="200" 
                style="width: 100%" 
                placeholder="正常范围：60~100"
              />
            </a-form-item>
            
            <a-form-item label="空腹血糖 (mmol/L)" name="fastingBloodGlucose">
              <a-input-number 
                v-model:value="formData.fastingBloodGlucose" 
                :min="1" 
                :max="30" 
                :step="0.1"
                style="width: 100%" 
                placeholder="正常范围：3.9~6.1"
              />
            </a-form-item>
            
            <a-form-item label="餐后血糖 (mmol/L)" name="postprandialBloodGlucose">
              <a-input-number 
                v-model:value="formData.postprandialBloodGlucose" 
                :min="1" 
                :max="30" 
                :step="0.1"
                style="width: 100%" 
                placeholder="正常范围：＜7.8"
              />
            </a-form-item>
            
            <a-form-item label="糖化血红蛋白 (%)" name="glycatedHemoglobin">
              <a-input-number 
                v-model:value="formData.glycatedHemoglobin" 
                :min="3" 
                :max="15" 
                :step="0.1"
                style="width: 100%" 
                placeholder="正常范围：4.0~5.6"
              />
            </a-form-item>
            
            <a-form-item label="血糖测量时间" name="glucoseMeasureTime">
              <a-date-picker 
                v-model:value="formData.glucoseMeasureTime" 
                show-time 
                style="width: 100%" 
                placeholder="请选择测量时间"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
    
    <!-- 记录表格 -->
    <div class="table-container">
      <a-table
        :columns="columns"
        :data-source="healthList"
        :row-key="record => record.id"
        :pagination="pagination"
        :loading="loading"
        :customRow="customRow"
        bordered
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'birthday'">
            {{ formatDate(record.birthday) }}
          </template>
          <template v-else-if="column.dataIndex === 'glucoseMeasureTime'">
            {{ formatDateTime(record.glucoseMeasureTime) }}
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <a-space>
              <a-button 
                type="link" 
                size="small" 
                @click="onRowClick(record)"
              >
                查看诊断
              </a-button>
              <a-popconfirm 
                title="确定要删除这条记录吗？" 
                @confirm="handleDelete(record.id)"
              >
                <a-button type="link" danger size="small">删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
          <template v-else-if="column.dataIndex === 'bloodPressure'">
            {{ record.bloodPressure || '-' }}
          </template>
          <template v-else-if="column.dataIndex === 'heartRate'">
            {{ record.heartRate || record.heartRate === 0 ? record.heartRate : '-' }}
          </template>
          <template v-else>
            {{ record[column.dataIndex] || '-' }}
          </template>
        </template>
        
        <template #emptyText>
          <a-empty description="暂无健康记录">
            <a-button type="primary" @click="showModal = true">新增记录</a-button>
          </a-empty>
        </template>
      </a-table>
    </div>
    
    <!-- 诊断报告模态框 -->
    <a-modal
      v-model:visible="diagnosisModalVisible"
      :title="diagnosisTitle"
      width="900px"
      :footer="null"
      :maskClosable="false"
      @cancel="handleDiagnosisModalClose"
    >
      <a-spin :spinning="diagnosisLoading || rediagnoseLoading">
        <div v-if="diagnosisResult" class="diagnosis-content">
          <!-- 基本信息部分 -->
          <a-descriptions 
            bordered 
            :column="1" 
            size="middle" 
            title="患者基本信息"
          >
            <a-descriptions-item label="性别">
              {{ diagnosisRecordData?.gender || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="年龄">
              {{ diagnosisRecordData?.birthday ? calculateAge(diagnosisRecordData.birthday) : '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="身高">
              {{ diagnosisRecordData?.height || '-' }} cm
            </a-descriptions-item>
            <a-descriptions-item label="体重">
              {{ diagnosisRecordData?.weight || '-' }} kg
            </a-descriptions-item>
            <a-descriptions-item label="BMI">
              {{ diagnosisRecordData?.height && diagnosisRecordData?.weight 
                ? (diagnosisRecordData.weight / ((diagnosisRecordData.height/100) ** 2)).toFixed(1) 
                : '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="血型">
              {{ diagnosisRecordData?.bloodType || '-' }}
            </a-descriptions-item>
          </a-descriptions>
          
          <a-divider />
          
          <!-- 诊断结果部分 -->
          <div class="section">
            <h3 class="section-title">诊断报告</h3>
            <div class="section-content markdown-body" v-html="diagnosisResultHtml"></div>
          </div>
          
          <div class="diagnosis-footer">
            <a-space>
              <a-button @click="handleDiagnosisModalClose">关闭</a-button>
              <a-button 
                type="primary" 
                @click="handleRediagnose"
                :loading="rediagnoseLoading"
              >
                重新诊断
              </a-button>
            </a-space>
          </div>
        </div>
        
        <div v-else class="no-diagnosis">
          <a-empty description="当前记录尚未生成诊断报告">
            <template #image>
              <icon-health style="font-size: 48px; color: #1890ff;" />
            </template>
          </a-empty>
          <div class="action-text">是否现在进行健康诊断分析？</div>
          <div class="action-buttons">
            <a-button type="primary" @click="handleInitialDiagnose" :loading="diagnosisLoading">
              开始诊断
            </a-button>
            <a-button @click="handleDiagnosisModalClose" style="margin-left: 16px;">
              稍后再说
            </a-button>
          </div>
        </div>
      </a-spin>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { marked } from 'marked'

const API_URL = 'http://192.168.0.22:7044/api/module/AIHealthManage'

// 健康记录状态
const healthList = ref([])
const loading = ref(false)
const showModal = ref(false)
const saving = ref(false)
const formData = reactive({
  gender: '',
  birthday: null,
  height: null,
  weight: null,
  bloodType: '',
  bloodPressure: '',
  heartRate: null,
  fastingBloodGlucose: null,
  postprandialBloodGlucose: null,
  randomBloodGlucose: null,
  glycatedHemoglobin: null,
  glucoseMeasureTime: null,
})

// 表格分页
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50'],
  showTotal: total => `共 ${total} 条记录`
})

// 诊断状态
const diagnosisModalVisible = ref(false)
const diagnosisLoading = ref(false)
const rediagnoseLoading = ref(false)
const diagnosisResult = ref('')
const diagnosisRecordId = ref(null)
const diagnosisRecordData = ref(null)
const diagnosisTitle = ref('健康诊断报告')

const columns = [
  { title: '性别', dataIndex: 'gender', width: 80 },
  { title: '生日', dataIndex: 'birthday', width: 120 },
  { title: '身高(cm)', dataIndex: 'height', width: 100 },
  { title: '体重(kg)', dataIndex: 'weight', width: 100 },
  { title: '血型', dataIndex: 'bloodType', width: 80 },
  { title: '血压', dataIndex: 'bloodPressure', width: 100 },
  { title: '心率', dataIndex: 'heartRate', width: 80 },
  { title: '空腹血糖', dataIndex: 'fastingBloodGlucose', width: 100 },
  { title: '糖化血红蛋白', dataIndex: 'glycatedHemoglobin', width: 120 },
  { title: '测量时间', dataIndex: 'glucoseMeasureTime', width: 180 },
  { 
    title: '操作', 
    dataIndex: 'action', 
    width: 150,
    fixed: 'right'
  }
]

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  return dayjs(dateString).format('YYYY-MM-DD')
}

// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return '-'
  return dayjs(dateString).format('YYYY-MM-DD HH:mm')
}

// 禁用未来日期
const disabledBirthdayDate = (current) => {
  return current && current > dayjs().endOf('day')
}

// 表格行点击处理
const customRow = (record) => {
  return {
    onClick: (event) => {
      if (event.target.closest('.ant-btn')) return
      onRowClick(record)
    }
  }
}

// 表格分页变化
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchHealthList()
}

// 获取健康记录列表
const fetchHealthList = async () => {
  loading.value = true
  try {
    const token = localStorage.getItem('accessToken')
    const res = await fetch(
      `${API_URL}/Page?PageNumber=${pagination.current}&PageSize=${pagination.pageSize}&OrderBy=Id&SortDirection=Descending`,
      {
        headers: {
          'Authorization': token ? `Bearer ${token}` : ''
        }
      }
    )
    const data = await res.json()
    
    if (data.success) {
      healthList.value = data.data || []
      pagination.total = data.totalCount || 0
    } else {
      message.error(data.message || '获取健康记录失败')
    }
  } catch (e) {
    message.error('网络请求失败')
  } finally {
    loading.value = false
  }
}

// 提交健康记录表单
const submitForm = async () => {
  saving.value = true
  try {
    const token = localStorage.getItem('accessToken')
    const payload = preparePayload()
    
    const res = await fetch(API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token ? `Bearer ${token}` : ''
      },
      body: JSON.stringify(payload),
    })
    
    const data = await res.json()
    if (data.success) {
      message.success('健康记录保存成功')
      showModal.value = false
      resetForm()
      fetchHealthList()
    } else {
      message.error(data.message || '保存失败')
    }
  } catch (error) {
    message.error('网络请求失败')
    console.error('提交错误:', error)
  } finally {
    saving.value = false
  }
}

// 准备表单数据
const preparePayload = () => {
  const payload = { ...formData }
  
  
  if (payload.birthday) {
    payload.birthday = dayjs(payload.birthday).format('YYYY-MM-DDTHH:mm:ss.SSSZ')
  }
  if (payload.glucoseMeasureTime) {
    payload.glucoseMeasureTime = dayjs(payload.glucoseMeasureTime).format('YYYY-MM-DDTHH:mm:ss.SSSZ')
  }
 
  const numberFields = [
    'height', 'weight', 'heartRate', 'fastingBloodGlucose',
    'postprandialBloodGlucose', 'randomBloodGlucose', 'glycatedHemoglobin'
  ]
  
  numberFields.forEach(field => {
    if (payload[field] === null || payload[field] === undefined) {
      payload[field] = 0
    }
  })
  
  const stringFields = ['bloodType', 'bloodPressure']
  stringFields.forEach(field => {
    if (payload[field] === null || payload[field] === undefined) {
      payload[field] = ''
    }
  })
  
  return payload
}

// 重置表单
const resetForm = () => {
  Object.keys(formData).forEach(key => {
    formData[key] = null
  })
  formData.gender = ''
  formData.bloodType = ''
  formData.bloodPressure = ''
}

// 取消表单
const handleCancel = () => {
  showModal.value = false
  resetForm()
}

// 删除健康记录
const handleDelete = async (id) => {
  try {
    const token = localStorage.getItem('accessToken')
    const res = await fetch(`${API_URL}/${id}`, {
      method: 'DELETE',
      headers: {
        'Authorization': token ? `Bearer ${token}` : ''
      }
    })
    const data = await res.json()
    
    if (data.success) {
      message.success('删除成功')
      fetchHealthList()
    } else {
      message.error(data.message || '删除失败')
    }
  } catch (e) {
    message.error('网络请求失败')
  }
}

// 获取诊断结果
const fetchDiagnosisResult = async (id, isRediagnose = false) => {
  const loadingType = isRediagnose ? rediagnoseLoading : diagnosisLoading
  loadingType.value = true
  try {
    const token = localStorage.getItem('accessToken')

    const res = await fetch(`${API_URL}/Resuts/${id}/${isRediagnose}`, {
      headers: {
        'accept': 'application/json',
        'Authorization': token ? `Bearer ${token}` : ''
      }
    })
    if (!res.ok) {
      message.error(`诊断请求失败，状态码：${res.status}`)
      diagnosisResult.value = null
      return
    }
    let data
    try {
      data = await res.json()
    } catch (jsonErr) {
      message.error('诊断请求响应格式错误，无法解析')
      diagnosisResult.value = null
      return
    }
    if (data.success && data.data && data.data.result) {
      diagnosisResult.value = data.data.result
      if (diagnosisRecordData.value) {
        diagnosisRecordData.value.result = data.data.result
      }
      message.success('诊断完成')
    } else {
      diagnosisResult.value = null
      message.error((data && data.message) || '获取诊断结果失败')
    }
  } catch (error) {
    diagnosisResult.value = null
    message.error('诊断请求异常')
    console.error('诊断请求错误:', error)
  } finally {
    loadingType.value = false
  }
}

// 初始诊断
const handleInitialDiagnose = async () => {
  if (diagnosisRecordId.value) {
    await fetchDiagnosisResult(diagnosisRecordId.value, true)
  }
}

// 重新诊断
const handleRediagnose = async () => {
  if (diagnosisRecordId.value) {
    await fetchDiagnosisResult(diagnosisRecordId.value, true)
  }
}

// 计算年龄
const calculateAge = (birthday) => {
  if (!birthday) return '-'
  const birthDate = new Date(birthday)
  const today = new Date()
  let age = today.getFullYear() - birthDate.getFullYear()
  const monthDiff = today.getMonth() - birthDate.getMonth()
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--
  }
  return age + '岁'
}

// 关闭诊断模态框
const handleDiagnosisModalClose = () => {
  diagnosisModalVisible.value = false
  diagnosisResult.value = ''
  diagnosisRecordId.value = null
  diagnosisRecordData.value = null
  diagnosisTitle.value = '健康诊断报告'
  rediagnoseLoading.value = false
}

// 表格行点击，弹出诊断模态框并加载详情
const onRowClick = async (record) => {
  diagnosisModalVisible.value = true
  diagnosisTitle.value = '健康诊断报告'
  diagnosisRecordId.value = record.id
  diagnosisRecordData.value = null
  diagnosisResult.value = ''
  diagnosisLoading.value = true
  try {
    const token = localStorage.getItem('accessToken')
    const res = await fetch(`${API_URL}/${record.id}`, {
      headers: {
        'accept': 'text/plain',
        'Authorization': token ? `Bearer ${token}` : ''
      }
    })
    const data = await res.json()
    if (data.success && data.data) {
      diagnosisRecordData.value = data.data
      if (data.data.result && data.data.result.trim() !== '') {
        diagnosisResult.value = data.data.result
      } else {
        diagnosisResult.value = null
      }
    } else {
      diagnosisResult.value = null
      message.error(data.message || '获取健康记录详情失败')
    }
  } catch (error) {
    diagnosisResult.value = null
    message.error('网络请求失败')
  } finally {
    diagnosisLoading.value = false
  }
}


const diagnosisResultHtml = computed(() => {
  if (!diagnosisResult.value) return ''
  const cleaned = diagnosisResult.value.replace(/<think>[\s\S]*?<\/think>/gi, '')
  return marked.parse(cleaned)
})

onMounted(() => {
  fetchHealthList()
})
</script>

<style scoped>
.action-bar {
  margin-bottom: 16px;
  display: flex;
  justify-content: flex-end;
}

.table-container {
  margin-top: 16px;
}

.diagnosis-content {
  max-height: 70vh;
  overflow-y: auto;
  padding: 8px;
}

.diagnosis-content pre {
  background: #f5f5f5;
  padding: 16px;
  border-radius: 4px;
  font-size: 14px;
  line-height: 1.6;
  color: #333;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.section {
  margin-bottom: 24px;
}

.section-title {
  color: #1890ff;
  margin-bottom: 12px;
  font-size: 16px;
  font-weight: 500;
  border-left: 4px solid #1890ff;
  padding-left: 8px;
}

.section-content {
  line-height: 1.8;
  font-size: 14px;
  color: #333;
}

.diagnosis-footer {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
  text-align: right;
}

.no-diagnosis {
  text-align: center;
  padding: 40px 0;
}

.action-text {
  margin: 16px 0;
  font-size: 16px;
  color: #666;
}

.action-buttons {
  margin-top: 24px;
}

.loading-container {
  padding: 40px 0;
  text-align: center;
}


.diagnosis-result {
  font-size: 14px;
  line-height: 1.6;
  color: #333;
}

.markdown-body {
  font-size: 15px;
  line-height: 1.8;
  color: #333;
  background: #fafcff;
  padding: 16px;
  border-radius: 6px;
  word-break: break-all;
}
.markdown-body h1,
.markdown-body h2,
.markdown-body h3 {
  color: #1890ff;
  margin-top: 18px;
  margin-bottom: 10px;
  font-weight: 600;
}
.markdown-body ul,
.markdown-body ol {
  margin: 10px 0 10px 24px;
}
.markdown-body li {
  margin-bottom: 6px;
}
.markdown-body strong {
  color: #d46b08;
}
.markdown-body hr {
  border: none;
  border-top: 1px solid #e8e8e8;
  margin: 18px 0;
}
.markdown-body code,
.markdown-body pre {
  background: #f5f5f5;
  border-radius: 3px;
  padding: 2px 6px;
  font-size: 13px;
}
</style>